package com.cycle.community.controller.advice;

import com.cycle.community.constant.HttpConstant;
import com.cycle.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lenovo
 * @create 2022/8/15 17:20
 */
//不加参数，会扫描所有的bean
//只会扫描带有@Controller注解的bean
//不用在任何Controller加代码
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class})//所有异常
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常： " + e.getMessage());
        for (StackTraceElement element : e.getStackTrace()) {
            logger.error(element.toString());
        }
        //判断请求是普通请求还是异步请求
        String xRequestedWith = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(xRequestedWith)) {
//            response.setContentType("application/json");//浏览器会自动转为json
            response.setContentType("application/plain;charset=UTF-8");//普通字符串，浏览器需要人为转为json
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(HttpConstant.ERROR, "服务器异常"));
        } else {
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }
}
